<?php

namespace App\Http\Controllers\v1;


use App\Models\Area;
use App\Models\Banner;
use App\Models\Family;
use App\Models\ClaimProject;
use App\Models\ClaimProjectCategory;
use App\Models\ClaimProjectServiceObj;
use App\Models\Feeling;
use App\Models\FeelingComment;
use App\Models\FeelingLike;
use App\Models\Project;
use App\Models\SmsCode;
use App\Models\Team;
use App\Models\TeamCategory;
use App\Models\User;
use App\Models\UserClaimProject;
use App\Models\UserCollection;
use App\Models\UserInterface;
use App\Models\UserProject;
use App\Models\UserTeam;
use App\Models\Volunteer;
use App\Models\VolunteerGoodAt;
use EasyWeChat\Core\Exception;
use Illuminate\Http\Request;
use App\Libs\IdCard;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Hashids\Hashids;

class FeelingController extends Controller
{

    public function index(Request $request)
    {
        $rules = ['type' => 'in:1,2,3', 'relation_id'=> $request->has('type') && $request->input('type') != 1?'required': '', ];
        $validator = Validator::make(Input::all(), $rules);
        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }

        $userInfo = User::where('token', $this->getToken())->first();
        $userId = empty($userInfo)? 0:$userInfo->id;

        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 10);
        $from = ($pageNum - 1)*$pageSize;

        $nodes = Feeling::where('is_display', 1)->where('org_id', $this->getOrdId());

        if($request->has('type'))
        {
            $nodes = $nodes->where('type', $request->input('type'));
        }

        if($request->has('relation_id'))
        {
            $nodes = $nodes->where('relation_id', $request->input('relation_id'));
        }

        $count = $nodes->count();
        $nodes = $nodes->orderBy('id', 'desc');

        $lists = $nodes->take($pageSize)->skip($from)->get();
        $list = [];
        foreach($lists as $value)
        {
            if(method_exists($value, 'getAllInfo'))
            {
                $tmp = $value->getAllInfo($userId);
                $list[] = $tmp;
            }
        }

        $pageInfo = [
            "current_page" => intval($pageNum),
            "total_page" => ceil($count / $pageSize),
            "page_size" => intval($pageSize)
        ];

        $data['list'] = $list;
        $data['page'] = $pageInfo;
        $this->setData($data);

        return $this->response();

    }

    public function info(Request $request, $id)
    {
        $feeling = Feeling::where('id', $id)->where('is_display', 1)->first();

        if(empty($feeling))
        {
            $this->setStatus(10001);
            $this->setMsg('id错误');
            return $this->response();
        }

        $userInfo = User::where('token', $this->getToken())->first();
        $userId = empty($userInfo)? 0:$userInfo->id;
        $data = $feeling->getAllInfo($userId);


        $this->setData($data);

        return $this->response();
    }

    public function store(Request $request)
    {
        $rules = ['type' => 'required|in:1,2,3', 'relation_id'=> $request->input('type') != 1?'required': '', 'content'=>empty($request->input('photo'))? 'required':'', 'photo'=>empty($request->input('content'))? 'required|array':'array', ];
        $validator = Validator::make(Input::all(), $rules);
        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }

        $userInfo = User::where('token', $this->getToken())->first();

        $relationId = $request->input('relation_id');

        //添加判断
        switch ($request->input('type'))
        {
            case 2:
                $relation = Project::where('id', $relationId)->where('org_id', $this->getOrdId())->first();
                $isJoin = UserProject::where('user_id', $userInfo->id)->where('project_id', $relationId)->where('verify_status', 1)->count();

                if($isJoin == 0)
                {
                    $this->setStatus(10001);
                    $this->setMsg('您没加入该项目，无法在项目社区发言');

                    return $this->response();
                }

                break;

            case 3:
                $relation = Team::where('id', $relationId)->where('org_id', $this->getOrdId())->first();
                $isJoin = UserTeam::where('team_id', $relationId)->where('user_id', $userInfo->id)->where('verify_status', 1)->count();

                if($isJoin == 0)
                {
                    $this->setStatus(10001);
                    $this->setMsg('您没加入该团队，无法在团队社区发言');

                    return $this->response();
                }
                break;
        }

        if( $request->input('type') != 1 && empty($relation) )
        {
            $this->setStatus(10001);
            $this->setMsg('非法的relation id');

            return $this->response();
        }

        $data = array_only($request->all(), ['type', 'relation_id', 'content', 'photo']);

        $data['user_id'] = $userInfo->id;
        $data['org_id'] = $this->getOrdId();

        $feeling = new Feeling();
        $feeling->fill($data)->save();

        $feeling = Feeling::find($feeling->id);

        $this->setData($feeling->getAllInfo($userInfo->id));

        return $this->response();
    }

    public function delete(Request $request, $id)
    {
        $userInfo = User::where('token', $this->getToken())->first();
        $feeling = Feeling::find($id);

        if($userInfo->id == $feeling->user_id)
        {
            $feeling->is_display = 0;
            $feeling->save();
            return $this->response();
        }

        $this->setStatus(10001);
        $this->setMsg('权限错误');
        return $this->response();
    }


    public function like(Request $request, $id)
    {
        $userInfo = User::where('token', $this->getToken())->first();

        $feeling = Feeling::find($id);
        $ct = DB::table('feeling_tone_like')->where('feeling_id', $feeling->id)->where('user_id', $userInfo->id)->count();

        if($ct == 0)
        {
            DB::table('feeling_tone_like')->insert(['feeling_id'=>$id, 'user_id'=>$userInfo->id]);
            $feeling->syncLikeCount();
        }

        return $this->response();
    }

    public function dislike(Request $request, $id)
    {
        $userInfo = User::where('token', $this->getToken())->first();

        $feeling = Feeling::find($id);

        DB::table('feeling_tone_like')->where('feeling_id', $feeling->id)->where('user_id', $userInfo->id)->delete();

        $feeling->syncLikeCount();

        return $this->response();
    }

    public function my(Request $request)
    {
        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 10);
        $from = ($pageNum - 1)*$pageSize;

        $userInfo = User::where('token', $this->getToken())->first();

        $userInterface = UserInterface::where('type', 2)->where('user_id', $userInfo->id)->first();

        $lastTime = empty($userInterface)? 0:$userInterface->last_time;
        $newCommentCt = FeelingComment::where('created_at', '>',  date('Y-m-d H:i:s', $lastTime))->where(function($query) use ($userInfo){
            $query->whereRaw("feeling_id in (select id from feeling_tone where user_id={$userInfo->id})")->orWhereRaw("parent_id in (select id from feeling_tone_comment where user_id={$userInfo->id})");
        })->where('user_id', '!=', $userInfo->id)->count();

        //$newLike = FeelingLike::where('created_at', '>', date('Y-m-d H:i:s', $lastTime))->where(function($query) use ($userInfo) {
        //    $query->whereRaw("feeling_id in (select id from feeling_tone where user_id={$userInfo->id})");
        //})->count();

        $nodes = Feeling::where('is_display', 1)->where('user_id', $userInfo->id);
        $count = $nodes->count();
        $nodes = $nodes->orderBy('id', 'desc');

        $lists = $nodes->take($pageSize)->skip($from)->get();
        $list = [];
        foreach($lists as $value)
        {
            if(is_object($value))
            {
                $tmp = $value->getAllInfo($userInfo->id);
                $list[] = $tmp;
            }

        }

        $pageInfo = [
            "current_page" => intval($pageNum),
            "total_page" => ceil($count / $pageSize),
            "page_size" => intval($pageSize)
        ];

        $data['list'] = $list;
        $data['new_comment'] = $newCommentCt;
        $data['page'] = $pageInfo;
        $this->setData($data);

        return $this->response();
    }

    public function comment(Request $request, $id)
    {
        $rules = ['comment' => 'required',  ];
        $validator = Validator::make(Input::all(), $rules);
        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }
        $userInfo = User::where('token', $this->getToken())->first();
        $feeling = Feeling::find($id);

        if($feeling->type == 2)
        {
            $relation = Project::where('id', $feeling->relation_id)->where('org_id', $this->getOrdId())->first();
            $isJoin = UserProject::where('user_id', $userInfo->id)->where('project_id', $feeling->relation_id)->where('verify_status', 1)->count();

            if($isJoin == 0)
            {
                $this->setStatus(10001);
                $this->setMsg('您没加入该项目，无法在项目社区发言');

                return $this->response();
            }
        }elseif($feeling->type == 3)
        {
            $relation = Team::where('id', $feeling->relation_id)->where('org_id', $this->getOrdId())->first();
            $isJoin = UserTeam::where('team_id', $feeling->relation_id)->where('user_id', $userInfo->id)->where('verify_status', 1)->count();

            if($isJoin == 0)
            {
                $this->setStatus(10001);
                $this->setMsg('您没加入该团队，无法在团队社区发言');

                return $this->response();
            }
        }

        $parentId = $request->input('parent_id', 0);
        $comment = $request->input('comment');

        if($parentId > 0)
        {
            $p = FeelingComment::where('feeling_id', $id)->where('id', $parentId)->first();

            if(empty($p))
            {
                $this->setStatus(10001);
                $this->setMsg('非法的parent id');

                return $this->response();
            }
        }

        $c = new FeelingComment();
        $fill = [
            'user_id'=>$userInfo->id,
            'feeling_id'=>$id,
            'parent_id'=>$parentId,
            'comment'=>$comment,
        ];
        $c->fill($fill)->save();

        $feeling->syncCommentCount();
        $c = FeelingComment::find($c->id);

        $data = $c->getAllInfo($userInfo->id);
        $this->setData($data);
        return $this->response();
    }


    public function delcomment(Request $request, $id)
    {
        $userInfo = User::where('token', $this->getToken())->first();

        $fComment = FeelingComment::find($id);
        
        if($fComment->user_id != $userInfo->id)
        {
            $this->setStatus(10001);
            $this->setMsg('权限错误');

            return $this->response();
        }

        $fComment->is_display = 0;
        $fComment->save();
        $feeling = Feeling::find($fComment->feeling_id);
        $feeling->syncCommentCount();

        return $this->response();
    }

    public function newcomment(Request $request)
    {
        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 20);
        $from = ($pageNum - 1)*$pageSize;

        $userInfo = User::where('token', $this->getToken())->first();
        $userInterface = UserInterface::where('type', 2)->where('user_id', $userInfo->id)->first();
        if(empty($userInterface))
        {
            $userInterface = new UserInterface();
            $userInterface->fill(['user_id'=>$userInfo->id, 'type'=>2, 'last_time'=>0]);//对last_time赋值，兼容处理
        }
        $lastTime = $userInterface->last_time;
        $userInterface->fill(['last_time'=>time()]);

        $userInterface->save();


        //comment
        $nodes = FeelingComment::where('user_id', '!=', $userInfo->id);
        $nodes = $nodes->where(function($query) use ($userInfo){
            $query->whereRaw("feeling_id in (select id from feeling_tone where user_id={$userInfo->id})")->orWhereRaw("parent_id in (select id from feeling_tone_comment where user_id={$userInfo->id})");
        });
        $count = $nodes->count();
        $nodes = $nodes->orderBy('id', 'desc');
        $lists = $nodes->take($pageSize)->skip($from)->get();

        $list = [];
        foreach($lists as $value)
        {
            $tmp = $value->getAllInfo($userInfo->id);
            $tmp['feeling'] = Feeling::format($value->feeling);
            $tmp['is_new'] = $value->created_at >  date('Y-m-d H:i:s', $lastTime)? 1:0;
            $list[] = $tmp;
        }

        //like
        //$lists = FeelingLike::where('created_at', '>', $lastTime)->where(function($query) use ($userInfo) {
        //    $query->whereRaw("feeling_id in (select id from feeling_tone where user_id={$userInfo->id})");
        //})->orderBy('id', 'desc')->get();
        //foreach($lists as $value)
        //{
        //    $tmp = $value->getAllInfo($userInfo->id);
        //    $tmp['feeling'] = Feeling::format($value->feeling);
        //    $list[] = $tmp;
        //}

        //usort($list, function($a, $b){
        //    return $a['created_at'] > $b['created_at']? -1:1;
        //});

        $pageInfo = [
            "current_page" => intval($pageNum),
            "total_page" => ceil($count / $pageSize),
            "page_size" => intval($pageSize)
        ];
        $data['list'] = $list;
        $data['page'] = $pageInfo;

        $this->setData($data);
        return $this->response();
    }


}
